# -*- coding: utf-8 -*-
"""
Created on Mon Mar  8 16:06:16 2021

@author: Think
"""
'''
import lhsmdu
import matplotlib.pyplot as plt
import numpy

lam = lhsmdu.sample(5,10) # Latin Hypercube Sampling of two variables, and 10 samples each.
k = lhsmdu.createRandomStandardUniformMatrix(5,10) # Monte Carlo Sampling

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0,1,0.1))
ax.set_yticks(numpy.arange(0,1,0.1))
plt.scatter(k[0].tolist(), k[1].tolist(), color="b", label="LHS-MDU")
#plt.scatter(lam[0].tolist(), lam[1].tolist(), color="r", label="MC")
plt.grid()
plt.show()
'''

import numpy as np


def LHSample(D, bounds, N):
    '''
    :param D:参数个数
    :param bounds:参数对应范围（list）
    :param N:拉丁超立方层数
    :return:样本数据
    '''

    result = np.empty([N, D])
    temp = np.empty([N])
    d = 1.0 / N

    for i in range(D):

        for j in range(N):
            temp[j] = np.random.uniform(
                low=j * d, high=(j + 1) * d, size=1)[0]

        np.random.shuffle(temp)

        for j in range(N):
            result[j, i] = temp[j]

    # 对样本数据进行拉伸
    b = np.array(bounds)
    lower_bounds = b[:, 0]
    upper_bounds = b[:, 1]
    if np.any(lower_bounds > upper_bounds):
        print('范围出错')
        return None

    #   sample * (upper_bound - lower_bound) + lower_bound
    np.add(np.multiply(result,
                       (upper_bounds - lower_bounds),
                       out=result),
           lower_bounds,
           out=result)
    return result


if __name__ == '__main__':
    D = 15
    N = 20
    bounds = [[10, 100], [10, 100], [10, 100], [10, 100], [0, 1], [10, 100], [1, 5], [1, 5], [0, 1], [100, 500], [0, 1],
              [2, 20], [1, 10], [10, 100], [0.1, 0.5]]
    samples = LHSample(D, bounds, N)
